package com.wwy.readwrite.utlis;

/**
 * @author 王伟羽
 * @program: readwrite-demo
 * @description:
 * @create: 2025/02/08
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 一个工具类，mybatis拦截器会把获取主库还是获取从库的通知放在这个类的contextHolder中，
 * 数据源路由器再从这个contextHolder中获取通知
 */
public class DynamicDataSourceHolder {
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSourceHolder.class);
    private static ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    public static final String DB_MASTER = "master";
    public static final String DB_SLAVE = "slave";

    /**
     * 获取线程的DbType
     * @return
     */
    public static String getDbType() {
        String result = contextHolder.get();
        if (result == null) {
            result = DB_MASTER;
        }
        return result;
    }

    /**
     * 设置线程的DbType
     * @param dbType
     */
    public static void setDbType(String dbType) {
        LOGGER.info("使用的数据源为：" + dbType);
        contextHolder.set(dbType);
    }

    /**
     * 清除数据源类型
     */
    public static void removeDbType() {
        contextHolder.remove();
    }
}
